package com.springcloud.springcloudprovider01.com.ded;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * Describle:
 * ClassName: LogAspect
 * Author: duende
 * DateTime: 2021/7/10 9:42
 */
@Aspect
@Component
public class LogAspect {

    @Pointcut("execution(public * com.springcloud.springcloudprovider01.com.ded..*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        ThreadLocalUtil.set("startTime", System.currentTimeMillis());
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        ThreadLocalUtil.set("name", request.getHeader("name") == null ? UUID.randomUUID().toString() : request.getHeader("name"));

    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(JoinPoint joinPoint, Object ret) throws Throwable {
        // 处理完请求，返回内容
//        Object[] object = joinPoint.getArgs();
//        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = attributes.getRequest();
//        StringBuffer requestUrl = new StringBuffer(request.getRequestURL());
//        if (!StringUtils.isEmpty(request.getQueryString()))
//            requestUrl.append("?").append(URLDecoder.decode(request.getQueryString(), "utf-8"));
//        //TODO 站位符：requesturl>methodType>DeclaringTypeName.SignatureName>requestparams>responseInfo>cost
//        Slf4jLogUtil.SimpleLogUtil.infoToController("{} {} {} {} {} {}", requestUrl.toString()
//                , request.getMethod(), joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()
//                , JSON.toJSONString(object), JSON.toJSONString(ret), (System.currentTimeMillis() - (long) ThreadLocalUtil.get("startTime")));
        ThreadLocalUtil.remove();
    }

}
